﻿using System;
using System.Collections.Generic;
using UnityEngine;
public class ActorManager : IInitByGameLevel, IDispose, ITick, ILogicUpdate
{
    public void AddActor(Actor actor) 
    {
        actor.InitByGameLevel(this._gameLevelMg);
        if (this.dicOfActors.ContainsKey(actor.Ident))
        {
            Debug.LogWarning($"[ActorManager] AddActor RepeatActorIdent oldActor:{this.dicOfActors[actor.Ident]?.Name},{this.dicOfActors[actor.Ident]?.Ident} new:{actor.Name} ident:{actor.Ident}");
            this.dicOfActors.Remove(actor.Ident);   
        }
        this.dicOfActors.Add(actor.Ident,actor);
        this.listOfActors.Add(actor);
    }
    public Actor GetActorByIdent(uint ident)
    {
        if (!this.dicOfActors.ContainsKey(ident)) 
        {
            return null;
        }
        return this.dicOfActors[ident];
    }
    public void RemoveActor(Actor actor) 
    {
        if (!this.dicOfActors.ContainsKey(actor.Ident))
        {
            return ;
        }
        this.dicOfActors.Remove(actor.Ident);
        this.listOfActors.Remove(actor);
    }
    //---------------------------------------------------------------
    public void Dispose()
    {
        DisposeActors();
    }
    public void InitByGameLevel(IGGameLevelMgr gameLevel)
    {
        this._gameLevelMg = gameLevel;
        this.InitActorContains();
    }
    private IGGameLevelMgr _gameLevelMg;
    public void LogicUpdate(float detlatime)
    {
        LogicUpdateActors(detlatime);
    }
    public void Tick()
    {
        TickActors();
    }

    //--------------------------------------------------------------
    private void TickActors()
    {
        int count = listOfActors.Count;
        for (int i = 0;i< count;++i) 
        {
            var actor = listOfActors[i];
            actor.Tick();
        }
    }
    private void LogicUpdateActors(float detlatime)
    {
        int count = listOfActors.Count;
        for (int i = 0; i < count; ++i)
        {
            var actor = listOfActors[i];
            actor.LogicUpdate(detlatime);
        }
    }
    private List<Actor> listOfActors = new List<Actor>(150);
    private Dictionary<uint,Actor> dicOfActors = new Dictionary<uint, Actor>(150);
    private void InitActorContains()
    {
        listOfActors.Clear();
        dicOfActors.Clear();
    }
    private void DisposeActors()
    {
        int count = listOfActors.Count;
        for (int i = 0; i < count; ++i)
        {
            var actor = listOfActors[i];
            actor.Dispose();
        }
    }

}
